package com.study.client.paho;



import com.study.client.common.constant.MqttQos;
import com.study.client.common.constant.SubscribeTopicConstant;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.paho.client.mqttv3.*;

import java.time.Instant;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 发布消息的回调类
 * <p>
 * 必须实现MqttCallback的接口并实现对应的相关接口方法CallBack 类将实现 MqttCallBack。
 * 每个客户机标识都需要一个回调实例。在此示例中，构造函数传递客户机标识以另存为实例数据。
 * 在回调中，将它用来标识已经启动了该回调的哪个实例。
 * 必须在回调类中实现三个方法：
 * <p>
 * public void messageArrived(MqttTopic topic, MqttMessage message)接收已经预订的发布。
 * <p>
 * public void connectionLost(Throwable cause)在断开连接时调用。
 * <p>
 * public void deliveryComplete(MqttDeliveryToken token))
 * 接收到已经发布的 QoS 1 或 QoS 2 消息的传递令牌时调用。
 * 由 MqttClient.connect 激活此回调。
 */
@Slf4j
@Data
public class SubscribeCallback implements MqttCallback {

    MqttClient clientMQTT;

    public SubscribeCallback(MqttClient clientMQTT) {
        
        this.clientMQTT = clientMQTT;
    }



/*    PointsService pointsService = SpringUtils.getBean(PointsService.class);
    AnalogValueService analogValueService = SpringUtils.getBean(AnalogValueService.class);
    DigitalValueService digitalValueService = SpringUtils.getBean(DigitalValueService.class);
    EnergyValueService energyValueService = SpringUtils.getBean(EnergyValueService.class);
    AnalogValueLatestService analogValueLatestService = SpringUtils.getBean(AnalogValueLatestService.class);
    DigitalValueLatestService digitalValueLatestService = SpringUtils.getBean(DigitalValueLatestService.class);
    EnergyValueLatestService energyValueLatestService = SpringUtils.getBean(EnergyValueLatestService.class);
    DataSourcesService dataSourcesService = SpringUtils.getBean(DataSourcesService.class);
    GatewaysService gatewaysService = SpringUtils.getBean(GatewaysService.class);
    EquipmentsService equipmentsService = SpringUtils.getBean(EquipmentsService.class);
    AlarmService alarmService = SpringUtils.getBean(AlarmService.class);*/

    Instant startTime;
    Instant endTime;

    private AtomicInteger count = new AtomicInteger(0);

    @Override
    public void connectionLost(Throwable cause) {
        log.info("Connection temporarily lost");
        // 连接丢失后，一般在这里面进行重连
        List<String> clientIds = ConnectFailureClient.clientIds;
        MqttClient client = this.getClientMQTT();
        if (clientIds.contains(client.getClientId())) {
            try {
                //client.disconnect();
                client.close();
            } catch (MqttException e) {
                e.printStackTrace();
            }

            ConnectFailureClient.clientIds.remove(client.getClientId());
            return;
        }
        try {
            log.info("Start reconnection");
            client.connect();
            client.subscribe(SubscribeTopicConstant.subscribeTopic, MqttQos.QOS1);
            client.subscribe(SubscribeTopicConstant.newDeviceSubscribeTopic, MqttQos.QOS1);
        } catch (MqttException e) {
            log.error("Reconnection failed : {}", e.toString());
        }

    }

    //（发布）publish后会执行到这里,发送状态
    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {
        log.info("deliveryComplete---------" + token.isComplete());
    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws MqttException {
        //startTime = Instant.now();
        String payload = new String(message.getPayload());
        if (StringUtils.isNotEmpty(payload)) {
            String sn = topic.split("/")[1];
            log.info(LocalDateTime.now().toString() + " Received from Topic :" + topic + " Received Message :" + payload);
            // subscribe后得到的消息会执行到这里面

            //新设备对接：厦门四信
            if(topic.startsWith("ems/sixin/")){
                log.info("congratulation:you have   a mqtt client!");
            }
           /* //新设备对接主题：配置
            else if(topic.startsWith("report/")){
                log.warn("测试新设备主题{}",topic);
            }*/
        }
    }


}